import os
from datetime import datetime
from typing import List

import akshare as ak
import pandas as pd

try:
    from notify_bark import BarkNotifier
except Exception:
    BarkNotifier = None  # type: ignore


def load_fund_codes_from_env() -> List[str]:
    codes = os.getenv("FUND_CODES", "").strip()
    if not codes:
        # default to codes used in your existing script
        return ['018994','018957','016371','017103','002112','001407','018123','022365','021528']
    # Allow separators: comma, space, semicolon
    parts = [p.strip() for p in codes.replace(";", ",").replace(" ", ",").split(",")]
    return [p for p in parts if p]


def format_message(df: pd.DataFrame) -> str:
    now_str = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    if df.empty:
        return f"[{now_str}] 未找到匹配基金代码的数据。"

    # Select important columns if exist
    candidate_cols = [
        "基金代码",
        "基金简称",
        "单位净值",
        "估算净值",
        "估算涨跌幅",
        "估算涨跌额",
        "估算时间",
    ]
    cols = [c for c in candidate_cols if c in df.columns]
    display_df = df[cols] if cols else df

    # Build compact lines
    lines: List[str] = [f"[{now_str}] 基金实时估值"]
    for _, row in display_df.iterrows():
        code = str(row.get("基金代码", "-"))
        name = str(row.get("基金简称", "-"))
        est_nv = row.get("估算净值", "-")
        est_chg = row.get("估算涨跌幅", "-")
        est_time = row.get("估算时间", "-")
        unit_nv = row.get("单位净值", "-")
        try:
            # Normalize percentage formatting if numeric
            if isinstance(est_chg, (int, float)):
                est_chg_str = f"{est_chg:.2f}%"
            else:
                est_chg_str = str(est_chg)
        except Exception:
            est_chg_str = str(est_chg)
        line = f"{code} {name} | 估值:{est_nv} 涨跌:{est_chg_str} 净值:{unit_nv} @ {est_time}"
        lines.append(line)
    return "\n".join(lines)


def fetch_fund_snapshot(fund_codes: List[str]) -> pd.DataFrame:
    df = ak.fund_value_estimation_em(symbol="全部")
    if not isinstance(df, pd.DataFrame) or df.empty:
        return pd.DataFrame()
    filtered = df.query('基金代码 in @fund_codes')
    return filtered.reset_index(drop=True)


def main() -> None:
    fund_codes = load_fund_codes_from_env()
    if BarkNotifier is None:
        raise RuntimeError("notify_bark.BarkNotifier not available. Ensure notify_bark.py exists.")
    notifier = BarkNotifier()
    df = fetch_fund_snapshot(fund_codes)
    message = format_message(df)
    notifier.send_message(title="基金实时估值", body=message)


if __name__ == "__main__":
    main()


